#include "spage.h"
#include "page.h"
#include "esp_log.h"
#include "page1.h"
#include "page2.h"
#include "page3.h"
#include "page4.h"
#include "page5.h"
#include "updata.h"
#include "esp_spiffs.h"
#include "esp_vfs.h"
#include "spage.h"
#include "esp_err.h"
#include "cJSON.h"
#include "mqtt_client.h"
#include "smqtt.h"
#include "file_server.h"
#include "wificonnet.h"
extern struct _blbl_sys_t blbl_sys_t;
page_t *page_head;
extern lv_obj_t * cont_head;
page_t * add_page(page_t * page)
{
    if(page==NULL)//页头初始化
    {
        page=(page_t *)malloc(sizeof(page_t));
        page->index=0;
        page->next=NULL;
        page->last=NULL;
        ESP_LOGI("SYSTEM","添加页面0");
        return page;
    }
    page_t *p,*now;//添加到page后
    now=page;					                       
	while(now->next!= NULL)		//找到同级菜单最后的表
    {
        now =now->next;
    }    
    p = (page_t *)malloc(sizeof(page_t));
    now->next=p;
    p->last=now;
    p->next=NULL;
    p->index=(now->index)+1;
    ESP_LOGI("SYSTEM","添加页面%d",p->index);
    return p;
}
page_t * lv_page_menu_init()
{
    page_head=add_page(page_head);//建立链表头部
    page_head->start=page1_start;
    page_head->end=page1_end;
    static page_t *page2;
    page2=add_page(page_head);
    page2->start=page2_start;
    page2->end=page2_end;
    static page_t *page4;
    page4=add_page(page_head);
    page4->start=page4_start;
    page4->end=page4_end;
    static page_t *page5;
    page5=add_page(page_head);
    page5->start=page5_start;
    page5->end=page5_end;
    return page_head;
}

void lv_page_clock_init()//闹钟信息获取
{
    //char info[15];
    // if(read_nvs("t_all",info))//获取哔哩哔哩uid
    // {
    //     sprintf(str,"%s%s%s",BILIBILI_REQUEST1,uid,BILIBILI_REQUEST2);
    //     ESP_LOGI(TAG_HTTP,"获取到uid");
    // }
}
esp_err_t cjson_mqtt(char *text,esp_mqtt_client_config_t *mqtt_cfg)
{
    
    cJSON *root_mqtt;
    char *index=strchr(text,'{');
    if(index==NULL)
    {
        return ESP_FAIL;
    }else
    {
        strcpy(text,index);
        root_mqtt = cJSON_Parse(text);
        if(root_mqtt!=NULL)
        {
            static char host[30];
            static char id[30];
            static char name[30];
            static char pwd[30];
            cJSON *js_host=cJSON_GetObjectItem( root_mqtt, "host");
            if(js_host==NULL)
            {
                ESP_LOGI("BLBL_MQTT", "JSON读取mqtt失败");
                return ESP_FAIL;
            }
            strcpy(host,js_host->valuestring);
            ESP_LOGI("BLBL_MQTT", "********host:%s*******",host);

            cJSON *js_id=cJSON_GetObjectItem( root_mqtt, "id");
            if(js_id==NULL)
            {
                ESP_LOGI("BLBL_MQTT", "JSON读取id失败");
                return ESP_FAIL;
            }
            strcpy(id,js_id->valuestring);
            ESP_LOGI("BLBL_MQTT", "********id%s*******",id);   

            cJSON *js_name=cJSON_GetObjectItem( root_mqtt, "name");
            if(js_name==NULL)
            {
                ESP_LOGI("BLBL_MQTT", "JSON读取name失败");
                return ESP_FAIL;
            }
            strcpy(name,js_name->valuestring);
            ESP_LOGI("BLBL_MQTT", "********name:%s**********",name);  

            cJSON *js_pwd=cJSON_GetObjectItem( root_mqtt, "pwd");
            if(js_pwd==NULL)
            {
                ESP_LOGI("BLBL_MQTT", "JSON读取密码失败");
                return ESP_FAIL;
            }
            strcpy(pwd,js_pwd->valuestring);
            ESP_LOGI("BLBL_MQTT", "********密码:%s**********",pwd);

            cJSON *js_keep=cJSON_GetObjectItem( root_mqtt, "keep");
            if(js_keep==NULL)
            {
                ESP_LOGI("BLBL_MQTT", "JSON读取keep失败");
                return ESP_FAIL;
            }

            mqtt_cfg->host = host;
            mqtt_cfg->username=name;
            mqtt_cfg->password=pwd;
            mqtt_cfg->client_id=id;
            mqtt_cfg->keepalive=js_keep->valueint;

        }else{
            return ESP_FAIL;
        }
        cJSON_Delete(root_mqtt);  
    }
    return ESP_OK;

}
esp_err_t cjson_clock(char *text,uint8_t clock_index)
{
    cJSON *root_clcok,*json_s,*json_h,*json_m;
    char *index=strchr(text,'{');
    if(index==NULL)
    {
        return ESP_FAIL;
    }else
    {
        strcpy(text,index);
        root_clcok = cJSON_Parse(text);
        if(root_clcok!=NULL)
        {
                json_s = cJSON_GetObjectItem(root_clcok, "s");
                blbl_sys_t.clock.clock[clock_index].state=json_s->valueint;         

                json_h = cJSON_GetObjectItem(root_clcok, "h");
                blbl_sys_t.clock.clock[clock_index].h=json_h->valueint;     

                json_m = cJSON_GetObjectItem(root_clcok, "m");
                blbl_sys_t.clock.clock[clock_index].m=json_m->valueint;     

                ESP_LOGI("CLOCK","***********clock%d ***********\n",clock_index);
                ESP_LOGI("CLOCK","*******state:%d h:%d m:%d ********\n",
                            blbl_sys_t.clock.clock[clock_index].state,
                            blbl_sys_t.clock.clock[clock_index].h,
                            blbl_sys_t.clock.clock[clock_index].m);
 
        }else{

                return ESP_FAIL;
        }
        cJSON_Delete(root_clcok);  
    }
    return ESP_OK;

}
esp_mqtt_client_config_t mqtt_cfg;
void mqtt_switch_save(uint8_t i)
{
    if(i)
    {
    save_nvs("mqtt","y");  
    lv_message("mqtt开启",500);      
    }
    else
    {
    save_nvs("mqtt","n");
    lv_message("mqtt关闭",500);
    }
    
}
void clock_switch_save(uint8_t i)
{
    if(i)
    {
    save_nvs("clock","y");  
    lv_message("闹钟开启",1000);      
    }
    else
    {
    save_nvs("clock","n");
    lv_message("闹钟关闭",1000);
    }
    
}
void web_temp_save(uint8_t i)
{
    if(i)
    {
    save_nvs("temp","y");  
    lv_message("温湿度上传开启",1000);      
    }
    else
    {
    save_nvs("temp","n");
    lv_message("温湿度上传关闭",1000);
    }
    
}
void web_switch_save(uint8_t i)
{
    if(i)
    {
    save_nvs("web","y");  
    lv_message("web开启",1000);      
    }
    else
    {
    save_nvs("web","n");
    lv_message("web关闭",1000);
    }
    
}
void lv_ico_mqtt_show(uint8_t state)
{
    if(state==1)
    {
	blbl_sys_t.ico.lv_mqtt = lv_label_create(cont_head, NULL);
    lv_label_set_recolor(blbl_sys_t.ico.lv_mqtt, true);
    lv_label_set_text(blbl_sys_t.ico.lv_mqtt, "#3CB371 " LV_SYMBOL_UPLOAD);        
    }
    else if(state==0)
    {
    if(blbl_sys_t.ico.lv_mqtt!=NULL) 
    {
	lv_obj_del(blbl_sys_t.ico.lv_mqtt); 
    blbl_sys_t.ico.lv_mqtt=NULL;       
    }


    }else if(state==3)//mqtt断开
    {
        lv_label_set_text(blbl_sys_t.ico.lv_mqtt, "#5CB371 " LV_SYMBOL_UPLOAD);
    }
    
}
void lv_ico_clock_show(uint8_t state)
{
    if(state)
    {
		blbl_sys_t.ico.lv_clock = lv_label_create(cont_head, NULL);
    	lv_label_set_recolor(blbl_sys_t.ico.lv_clock, true);
    	lv_label_set_text(blbl_sys_t.ico.lv_clock, "#3CB371 " LV_SYMBOL_BELL);      
    }
    else
    {
    if(blbl_sys_t.ico.lv_clock!=NULL) 
	lv_obj_del(blbl_sys_t.ico.lv_clock);
    }
    
}
void lv_ico_temp_show(uint8_t state)
{
    if(state)
    {
		blbl_sys_t.ico.lv_temp = lv_label_create(cont_head, NULL);
    	lv_label_set_recolor(blbl_sys_t.ico.lv_temp, true);
    	lv_label_set_text(blbl_sys_t.ico.lv_temp, "#3CB371 " LV_SYMBOL_REFRESH);      
    }
    else
    {
    if(blbl_sys_t.ico.lv_temp!=NULL) 
	lv_obj_del(blbl_sys_t.ico.lv_temp);
    }
    
}
void lv_ico_web_show(uint8_t state)
{
    if(state)
    {
		blbl_sys_t.ico.lv_web = lv_label_create(cont_head, NULL);
    	lv_label_set_recolor(blbl_sys_t.ico.lv_web, true);
    	lv_label_set_text(blbl_sys_t.ico.lv_web, "#3CB371 " LV_SYMBOL_DIRECTORY);      
    }
    else
    {
    if(blbl_sys_t.ico.lv_web!=NULL) 
	lv_obj_del(blbl_sys_t.ico.lv_web);
    }
    
}
void lv_blbl_mqtt_init()
{
    char info[250];
    if(read_nvs("mqtt",info))//读取mqtt状态
    {
        if(!strcmp("y",info))//开启mqtt
        {

            FILE* fp = fopen("/spiffs/mqtt.txt", "rb");
		    if (fp == NULL) {
				ESP_LOGI("MQTT", "mqtt文件找不到");
                blbl_sys_t.state.mqtt=0; 
				return ;
		    }
            fgets( info, 250,fp );
            if(cjson_mqtt(info,&mqtt_cfg)==ESP_OK)
            {
               	ESP_LOGI("MQTT", "获取mqtt账号密码"); 
            }
            else
            {
            blbl_sys_t.state.mqtt=0; 
            }    
            fclose(fp);
            mqtt_app_start(&mqtt_cfg);
            blbl_sys_t.state.mqtt=1; 
        }
        else//关闭mqtt
        {
            blbl_sys_t.state.mqtt=0;
        }
    }
    else//第一次使用mqtt未选择
    {
        blbl_sys_t.state.mqtt=0;        
        lv_message("mqtt未使用",500);
        save_nvs("mqtt","n");
    }
    if(blbl_sys_t.state.mqtt)//显示图标
    {
        lv_ico_mqtt_show(1);
    }
    
}
void save_clock(uint8_t clock_index,uint8_t s,uint8_t h,uint8_t m)
{
    char index[10];
    char info[30];
    if(h>23||m>60||s>2)
    {
        ESP_LOGI("CLOCK","保存时间格式错误1 s:%d,h:%d,m:%d",s,h,m);
        return;
    }
    sprintf(info,"{\"s\":%d,\"h\":%d,\"m\":%d}",s,h,m);
    sprintf(index,"ck%d",clock_index);
    save_nvs((const char *)index,info);

}
void lv_blbl_clock_init()
{
    char info[30];
    char index[10];
    if(read_nvs("clock",info))//读取闹钟状态
    {
        if(!strcmp("y",info))//开启闹钟
            blbl_sys_t.state.clock=1;
        else//关闭闹钟
            blbl_sys_t.state.clock=0;
        for(uint8_t i=0;i<2;i++)
        {
            sprintf(index,"ck%d",i);
            if(read_nvs((const char *)index,info))//读取闹钟1
            {
                if(cjson_clock(info,i)!=ESP_OK)
                {
                    ESP_LOGI("CLOCK","解析闹钟%d失败",i);                        
                    save_clock(i,0,0,0);//默认0点0分               
                }
                
            }else
            {
                 ESP_LOGI("CLOCK","读取闹钟%d失败",i);             
                  save_clock(i,0,0,0);//默认0点0分
 
            }
            
        }
    }
    else//第一次使用mqtt未选择
    {
        blbl_sys_t.state.clock=0;        
        save_nvs("clock","n");
    }
    if(blbl_sys_t.state.clock)//显示图标
    {
        lv_ico_clock_show(1);
    }
    
}
void lv_blbl_web_init()
{
    char info[5];
    if(read_nvs("web",info))//读取web状态
    {
        if(!strcmp("y",info))//开启web
        {
            if(start_file_server("/spiffs")!=ESP_OK)//启动文件系统
            {
            blbl_sys_t.state.web=0;     
            ESP_LOGI("web","web启动失败");     
            }
            blbl_sys_t.state.web=1;
        }
            
        else//关闭闹钟
            blbl_sys_t.state.web=0;
    }
    else//第一次使用mqtt未选择
    {
        blbl_sys_t.state.web=0;        
        save_nvs("web","n");
    }
    if(blbl_sys_t.state.web)//显示图标
    {
        lv_ico_web_show(1);
    }
    
}
void temp_upcloud()
{
    char info[30];
    if(read_nvs("temp",info))//读取温湿度上传状态
    {
        if(!strcmp("y",info))//开启上传
        {
            blbl_sys_t.state.upcloud=1;
        }
            
        else//关闭闹钟
            blbl_sys_t.state.upcloud=0;
    }
    else//第一次使用mqtt未选择
    {
        blbl_sys_t.state.upcloud=0;        
        save_nvs("temp","n");
    }
    if(blbl_sys_t.state.upcloud)//显示图标
    {
        lv_ico_temp_show(1);
    }
    
}    
void blbl_sys_info_init()
{
    blbl_sys_t.page=lv_page_menu_init();//建立菜单页
    blbl_sys_t.state.sys_button=0;
    blbl_sys_t.user_data=0;
    blbl_sys_t.wp.follow=get_value_blblfs(1);
    blbl_sys_t.wp.following=get_value_blblfs(0);
    lv_blbl_mqtt_init();
    lv_blbl_clock_init();
    lv_blbl_web_init();
    temp_upcloud();
}